/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import dao.Mahasiswa;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import model.DBKoneksi;

/**
 *
 * @author jarul
 */
public class MahasiswaImplements implements MahasiswaInterface {

    @Override
    public Mahasiswa insert(Mahasiswa mhs) throws SQLException {     
        PreparedStatement ps = DBKoneksi.getConnection().prepareStatement("INSERT INTO mahasiswa VALUES (?,?,?)");
        
        ps.setInt(1, mhs.getNim());
        ps.setString(2, mhs.getNama());
        ps.setString(3, mhs.getKelas());
        ps.executeUpdate();
        
        return mhs;
    }

    @Override
    public void update(Mahasiswa mhs) throws SQLException {
        PreparedStatement ps = DBKoneksi.getConnection().prepareStatement("UPDATE mahasiswa set nama=?, kelas=? WHERE nim=?");
        
        ps.setString(1, mhs.getNama());
        ps.setString(2, mhs.getKelas());
        ps.setInt(3, mhs.getNim());
        ps.executeUpdate();
    }

    @Override
    public void delete(int nim) throws SQLException {
        PreparedStatement ps = DBKoneksi.getConnection().prepareStatement("DELETE FROM mahasiswa WHERE nim=?");
        ps.setInt(1, nim);
        ps.executeUpdate();
    }

    @Override
    public List getAll() throws SQLException {
        Statement st = DBKoneksi.getConnection().createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM mahasiswa");
        
        List penampung = new ArrayList();
        
        while(rs.next()) {
            Mahasiswa mhs = new Mahasiswa();
            
            mhs.setNim(rs.getInt("nim"));
            mhs.setNama(rs.getString("nama"));
            mhs.setKelas(rs.getString("kelas"));
            penampung.add(mhs);
            
            // Cetak Ke Layar
            System.out.println("NIM Mahasiswa : " + rs.getInt("nim"));
            System.out.println("Nama Mahasiswa : " + rs.getString("nama"));
            System.out.println("Kelas Mahasiswa : " + rs.getString("kelas"));
            System.out.println("==========================================");
        }
        
        System.out.println("Jumlah Data : " + penampung.size());
        
        
        return penampung;
    }
    
    
}
